package com.woniuxy.kaer.user.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;

import com.woniuxy.kaer.commons.jwtUtil.JwtUtil;
import com.woniuxy.kaer.commons.util.Result;
import com.woniuxy.kaer.redis.util.RedisKey;
import com.woniuxy.kaer.user.dto.UserInfoDTO;

import com.woniuxy.kaer.user.form.*;
import com.woniuxy.kaer.user.param.*;
import com.woniuxy.kaer.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2025年02月17日
 */
@RestController
@RequestMapping("/userInfo")
@Api(tags = "用户信息接口")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //注册
    @ApiOperation(value = "注册")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterForm form) throws Exception {
        System.out.println(form);
        RegisterParam param = BeanUtil.toBean(form, RegisterParam.class);
        System.out.println(param);
        userInfoService.register(param);
        return Result.succeed("注册成功", null);
    }

    //账号密码登录
    @ApiOperation(value = "账号密码登录")
    @PostMapping("/userNameLogin")
    public Result userNameLogin(@RequestBody UserInfoLoginForm form, HttpServletResponse response) throws Exception {

            UserInfoLoginParam param = BeanUtil.toBean(form, UserInfoLoginParam.class);
            UserInfoDTO userInfoDTO = userInfoService.userNameLogin(param);
            //生成令牌
            Map<String, Object> body = BeanUtil.beanToMap(userInfoDTO);
            String accessToken = jwtUtil.createToken(body,15);
            String refreshToken = jwtUtil.createToken(body, 3*24*60);
            //保存短token
            stringRedisTemplate.opsForValue().set(RedisKey.REFRESH_ACCESS_EXPIRE(accessToken),refreshToken,3 * 24 * 60, TimeUnit.MINUTES);

            //保存长token
            stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(accessToken),"",30, TimeUnit.MINUTES);
            System.out.println("Access Token: " + accessToken);
            System.out.println("Refresh Token: " + refreshToken);
            response.setHeader("token", accessToken);
            response.setHeader("Access-Control-Expose-Headers","token");

            return Result.succeed("账号密码登录成功", userInfoDTO);
        }

        //验证码登录
        @ApiOperation(value = "验证码登录")
        @PostMapping("/verifyCodeLogin")
        public Result verifyCodeLogin(@RequestBody VerifyCodeForm form, HttpServletResponse response) throws Exception {
            VerifyCodeParam param = BeanUtil.toBean(form, VerifyCodeParam.class);
            UserInfoDTO userInfoDTO = userInfoService.verifyCodeLogin(param);
            //生成令牌
            Map<String, Object> body = BeanUtil.beanToMap(userInfoDTO);
            String accessToken = jwtUtil.createToken(body,15);
            String refreshToken = jwtUtil.createToken(body, 3*24*60);
            //保存短token
            stringRedisTemplate.opsForValue().set(RedisKey.REFRESH_ACCESS_EXPIRE(accessToken),refreshToken,3 * 24 * 60, TimeUnit.MINUTES);
            //保存长token
            stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(accessToken),"",30, TimeUnit.MINUTES);

            response.setHeader("token", accessToken);
            response.setHeader("Access-Control-Expose-Headers","token");
            return Result.succeed("验证码登录成功", userInfoDTO);
        }

        //发送登录验证码
        @GetMapping("/sendLoginVerifyCode")
        public Result sendLoginVerifyCode(String mobile)throws Exception{
            userInfoService.sendLoginVerifyCode(mobile);
            System.out.println();
            return Result.succeed("发送登录验证码成功", null);
        }

        //检查旧密码
        @ApiOperation(value = "检查旧密码")
        @GetMapping("/checkOldPassword")
        public Result checkOldPassword(String oldPassword, @RequestHeader("token") String token)throws Exception{
            Integer userId = jwtUtil.getUserId(token);
            userInfoService.checkOldPassword(userId, oldPassword);
            return Result.succeed("验证旧密码成功", null);
        }

        //修改密码
        @ApiOperation(value = "修改密码")
        @GetMapping("/changePassword")
        public Result changePassword(String newPassword,@RequestHeader("token") String token)throws Exception{
            Integer userId = jwtUtil.getUserId(token);
            userInfoService.changePassword(userId, newPassword);
            return Result.succeed("修改密码成功", null);
        }
        //上传头像
        @ApiOperation(value = "上传头像")
        @PostMapping("/uploadHeader")
        public Result uploadHeader( UpLoadHeaderForm form)throws Exception{
            //判断格式是否是png或jpg
            String type = FileTypeUtil.getType(form.getUserHeaderImage().getInputStream());
            if(!"png".equals(type) && !"jpg".equals(type)){
                throw new Exception("头像格式不正确");
            }
            UpLoadHeaderParam param = BeanUtil.toBean(form, UpLoadHeaderParam.class);
            userInfoService.uploadHeader(param);

            return Result.succeed("上传头像成功", null);
        }

        //获取用户个人信息
        @ApiOperation(value = "获取用户个人信息")
        @GetMapping("/selectSelf")
        public Result<UserInfoDTO> selectSelf(Integer userId)throws Exception{
            UserInfoDTO userInfoDTO = userInfoService.selectSelf(userId);
            System.out.println("123");
            return Result.succeed("获取用户个人信息成功", userInfoDTO);
        }

    @GetMapping("/queryUserInfo")
    public Result<UserInfoDTO> queryUserInfo(@RequestHeader("token") String token)throws Exception{
        Integer userId = jwtUtil.getUserId(token);
        UserInfoDTO userInfoDTO = userInfoService.selectSelf(userId);
        System.out.println("123");
        return Result.succeed("获取用户个人信息成功", userInfoDTO);
    }

        //修改用户积分
        @ApiOperation(value = "修改用户积分")
        @PutMapping("/updatePoint")
        public Result updatePoint(@RequestBody UpdatePointForm form)throws Exception{

            UpdatePointParam param = BeanUtil.toBean(form, UpdatePointParam.class);
            userInfoService.updatePoint(param);
            return Result.succeed("修改用户积分成功", null);
        }

//        //获取当前定位
//        @ApiOperation(value = "定位")
//        @GetMapping("/selectAddress")
//        public Result selectAddress(@RequestBody SelectAddressForm form) throws Exception{
//            SelectAddressParam param = BeanUtil.toBean(form, SelectAddressParam.class);
//            userInfoService.selectAddress(param);
//            return Result.succeed("定位成功", null);
//        }
    @ApiOperation(value = "定位")
    @GetMapping("/selectAddress")
    public Result selectAddress(@RequestBody SelectAddressForm form) throws Exception {

        SelectAddressParam param = new SelectAddressParam();
        param.setUserId(form.getUserId());
        param.setLocalLongitude(form.getLocalLongitude());
        param.setLocalLatitude(form.getLocalLatitude());
        param.setLocalAddress(form.getLocalAddress());
        userInfoService.selectAddress(param);  // 调用 Service 更新用户地址和经纬度
        return Result.succeed("定位成功", null);
    }



}


